<template>
  <view class="bluetooth-container">
    <!-- 连接状态按钮 -->
    <button :disabled="isScanning || isConnecting" @click="handleConnect">
      {{ currentStateText }}
    </button>

    <!-- 设备列表（弹窗显示） -->
    <uni-popup ref="devicePopup" :mask-click="false">
      <view class="device-popup">
        <view class="device-header">
          设备连接
          <uni-load-more
            v-if="isScanning && filteredDevices.length"
            class="icon-load"
            status="loading"
            :icon-size="16"
            :show-text="false"
          />
        </view>
        <view class="device-content">
          <scroll-view
            v-if="filteredDevices.length"
            scroll-y
            class="device-list"
          >
            <view
              v-for="(device, index) in filteredDevices"
              :key="device.deviceId || index"
              class="device-item"
              @click="selectDevice(device)"
            >
              <text class="device-name">{{ device.name || "未知设备" }}</text>
              <text class="device-rssi">信号强度: {{ device.RSSI }}dBm</text>
            </view>
          </scroll-view>
          <view
            v-if="!filteredDevices.length && isScanning"
            class="device-loading"
          >
            <view class="device-loading-txt">
              <uni-load-more
                class="mr-[10rpx]"
                status="loading"
                :icon-size="12"
                :show-text="false"
              />
              设备搜索中...
            </view>
          </view>
          <view
            v-if="!filteredDevices.length && !isScanning"
            class="device-empty"
          >
            未找到可用设备
          </view>
        </view>
        <view class="device-btn-box" @click="closeDevice">
          <view class="font-700 text-30rpx text-#666666"> 取消 </view>
        </view>
      </view>
    </uni-popup>

    <!-- 开始测量按钮 -->
    <button :disabled="!isConnecting" @click="startMeasurement">
      开始测量
    </button>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { BluetoothPlugin, ErrorTypes } from "@/utils/index";

const devicePopup = ref();

// 配置项
const config = {
  connectionMode: "manual", // 'auto' or 'manual'
  serviceId: "",
  onDeviceFound: (devices, deviceList) => {
    console.log("设备发现:", devices);
    console.log("设备列表:", deviceList);
  },
  characteristicMatch: (characteristics) => {
    const writeChar = characteristics.find((c) => c.properties.write);
    const notifyChar = characteristics.find((c) => c.properties.notify);
    return { writeChar, notifyChar };
  },
  communicationData: () => {
    let buffer = new ArrayBuffer(6);
    let dataView = new DataView(buffer);
    dataView.setUint8(0, 0x02);
    dataView.setUint8(1, 0x40);
    dataView.setUint8(2, 0xdc);
    dataView.setUint8(3, 0x01);
    dataView.setUint8(4, 0xa1);
    dataView.setUint8(5, 0x3c);
    return buffer;
  },
  reportDataHandler: (data) => {
    return data;
  },
  reportMethod: (data) => {
    console.log("Reporting data:", data);
  },
  errorHandler: (errorType, message, error) => {
    switch (errorType) {
      case ErrorTypes.BLUETOOTH_CONNECTION_FAILED:
        console.log('蓝牙连接失败:', message, error);
        break;
      case ErrorTypes.DEVICE_CONNECTION_FAILED:
        console.log('设备连接失败:', message, error);
        break;
      case ErrorTypes.DEVICE_NOT_FOUND:
        console.log('未找到设备:', message, error);
        break;
      // 其他异常类型处理
      default:
        console.log('未知异常:', message, error);
        break;
    }
  },
};

const {
  connectBluetooth,
  startBluetoothDiscovery,
  stopBluetoothDiscovery,
  connectDevice,
  disconnectDevice,
  startMeasurement: startMeasure,
  reportData,
} = BluetoothPlugin(config);

// 状态映射0:未连接蓝牙，1: 已连接蓝牙 2: 正在搜索设备 3: 已连接设备
const currentState = ref(0);
const isScanning = computed(() => currentState.value === 2);
const isConnecting = computed(() => currentState.value === 3);
const currentStateText = computed(() =>
  isScanning.value
    ? "蓝牙已连接，扫描中..."
    : isConnecting.value
    ? "已连接"
    : `点击连接${currentState.value == 1 ? '设备' : '蓝牙'}`
);

// 过滤后的设备列表（信号过滤+排序）
const deviceList = ref([]);
const filteredDevices = computed(() =>
  deviceList.value.filter((d) => d.RSSI > -80).sort((a, b) => b.RSSI - a.RSSI)
);

const showDeviceList = ref(false);

// 连接处理
const handleConnect = async () => {
  if (isConnecting.value) {
    return;
  }
  switch (currentState.value) {
    case 0:
      const isConnect = await connectBluetooth(); // 初始化蓝牙并开始扫描
      if (isConnect) {
        console.log("蓝牙成功");
        currentState.value = 1;
        devicePopup.value.open("center"); // 打开设备列表弹窗
        currentState.value = 2;
        await startBluetoothDiscovery(); // 开始扫描设备
      }
      break;

    case 1:
      devicePopup.value.open("center"); // 打开设备列表弹窗
      currentState.value = 2;
      await startBluetoothDiscovery(); // 开始扫描设备
      break;

    default:
      break;
  }
  try {

  } catch (error) {
    console.log("Error:", error);
  }
};

// 设备选择
const selectDevice = async (device) => {
  try {
    await connectDevice(device);
    currentState.value = 2;
    showDeviceList.value = false;
    console.log("连接成功");
  } catch (err) {
    console.log("连接失败:", err);
  }
};

// 取消连接
const closeDevice = () => {
  currentState.value = 1;
  stopBluetoothDiscovery()
  disconnectDevice()
  devicePopup.value.close();
}

// 开始测量
const startMeasurement = async () => {
  try {
    await startMeasure();
    console.log("开始测量");
    // 测量完成后上报数据
    await reportData();
  } catch (error) {
    console.log("测量失败:", error);
  }
};

onMounted(() => {})

// 页面卸载时清理资源
onUnmounted(() => {
  // 这里可以添加清理资源的逻辑
});
</script>

<style lang="scss" scoped>
.bluetooth-container {
  padding: 20px;
  text-align: center;
}

button {
  padding: 10px 20px;
  background-color: #1677ff;
  color: white;
  border-radius: 4px;
  border: none;
  margin-bottom: 10px;
}
.device-popup {
  background: #fff;
  border-radius: 24rpx;
  width: 90vw;
  height: 70vh;
  .device-header {
    padding: 0 32rpx;
    height: 100rpx;
    font-size: 34rpx;
    font-weight: 600;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
    .icon-load {
      margin-left: 10rpx;
    }
  }
  .device-content {
    height: calc(100% - 190rpx);
    .device-list {
      height: 100%;

      .device-item {
        padding: 28rpx 32rpx;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5f5;

        .device-name {
          flex: 1;
          font-size: 30rpx;
        }

        .device-rssi {
          color: #666;
          font-size: 26rpx;
        }
      }
    }
    .device-loading {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      &-hint {
        font-size: 30rpx;
        color: #333;
        font-weight: bold;
        line-height: 1.5;
      }
      &-txt {
        font-size: 28rpx;
        color: #999;
        margin-top: 30rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      &-img {
        width: 476rpx;
        height: 274rpx;
        margin: 14rpx 0;
      }
    }

    .device-empty {
      padding: 48rpx;
      color: #999;
      line-height: 1.6;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .device-btn-box {
    height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    border-top: 1rpx solid #ccc;
    color: #1677ff;
  }
}
</style>
